import os
import cv2
import subprocess
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from math import *
from cmath import phase
from pandas import DataFrame as df
from know import KNOW

T=1000*4*pi/1e7
_know=KNOW(36,50.0,1.0,10,50,150.0,15.0,5.0)
ZOOM,GROUND,TARGET=1,1200.0,64

plt.rcParams['font.size']=11
plt.rcParams['font.family']="Inconsolata"

path=os.path.join("datasetsedd","test")
fs=[fs for _,_,fs in os.walk(path)][0]
fs=[os.path.join(path,det) for det in fs if ".dat" in det]

for _,each in enumerate(fs[9:10]):
    print(_,each)
    basename=os.path.splitext(os.path.basename(each))[0]

    data=[]
    with open(os.path.join(path,basename,"forward","temp.res"),"r") as fp:
        data.extend([det.split() for det in fp])  
    data=[det for det in data if len(det)==11]
    data=np.array([[float(det[-3]),float(det[-2])] for _,det in enumerate(data)])
    data=data.reshape(data.shape[0]*data.shape[1])
    
    filenames=[filenames for _,_,filenames in os.walk(os.path.join(path,basename,"result"))][0]
    filenames=[det for det in filenames if ".pred" in det]
    filenames.sort(key=lambda x: os.path.getmtime(os.path.join(path,basename,"result",x)))
    
    ERROR,INDEX=100.0,0
    for i,row in enumerate(filenames[:]):
        print(row)
        preds=np.genfromtxt(os.path.join(path,basename,"result",row))
        nx,ny=_know.XRANGE,_know.NLAYER
        top_border,bottom_border,left_border,right_border=int((TARGET-ny*ZOOM)/2.),int((TARGET-ny*ZOOM)/2.),int((TARGET-nx*ZOOM)/2.),int((TARGET-nx*ZOOM)/2.)
        preds=preds[top_border:TARGET-bottom_border,left_border:TARGET-right_border]
        preds=np.log(((1.0-cv2.resize(preds,(nx,ny)))*GROUND))
        np.nan_to_num(preds,False,0.0) 
        with open(os.path.join(path,basename,"result","forward.mod"),"w") as fp:        
            fp.write(" ".join([str(det) for det in [_know.XRANGE,_know.NLAYER,"LOGE"]])+"\n")
            fp.write(" ".join([str(det) for det in _know.INTERVAL])+"\n")
            fp.write(" ".join([str(det) for det in _know.TIC])+"\n")
            np.savetxt(fp,preds)
        
        subprocess.run(["mt2di.exe","-F",os.path.join(path,basename,"result","forward.mod"),os.path.join(path,"temp.mea"),os.path.join(path,basename,"result","temp.res")],capture_output=False)
        content=[]
        with open(os.path.join(path,basename,"result","temp.res"),"r") as fp:
            content.extend([det.split() for det in fp])    
        content=[det for det in content if len(det)==11]
        forward=np.array([[float(det[-3]),float(det[-2])] for _,det in enumerate(content)])
        forward=forward.reshape(forward.shape[0]*forward.shape[1])
        
        rms=float(tf.reduce_mean(tf.reduce_sum(tf.square(np.array(forward).astype(np.float32)-np.array(data).astype(np.float32)))))
        
        if rms<ERROR:
            INDEX=i
            ERROR=rms
    
    print(filenames[INDEX],ERROR)